aspnetcore-angular-universal icon indicating copy to clipboard operation
aspnetcore-angular-universal copied to clipboard

Support for 404 Status Code

Open naveedahmed1 opened this issue 8 years ago • 3 comments

There should also be a support for setting proper status code especially in case of 404 not found errors.

I have seen some discussion about setting status codes here:

https://github.com/angular/universal/issues/667

And the service referred by @patrickmichalina seems awesome.

https://github.com/patrickmichalina/fusebox-angular-universal-starter/blob/master/src/client/app/shared/services/server-response.service.ts

To add its support I think it would require update to aspnetcore-engine.

@MarkPieszak @isaac2004

naveedahmed1 avatar Sep 28 '17 16:09 naveedahmed1

@MarkPieszak did you plan on doing this in engine?

isaacrlevin avatar Nov 13 '17 02:11 isaacrlevin

Must-have functionality for production use with SEO, voting up. For those who curious how it can be achieved right now, I made an really ugly hack until this will be implemented.

1) Set Whenever you need to set custom HTTP status code - add a meta.

@Component({
    selector: 'not-found-page',
    templateUrl: './not-found-page.view.html',
})
export class NotFoundPageComponent {
    constructor(meta: Meta, _config: AppConfig) {
        if (_config.isServer) {
            meta.addTag({ name: 'STATUS_CODE', content: '404' });
        }
    }
}

2) Parse Parse it at boot.server.ts, and set approciate statusCode when returning preprendering result.

 return ngAspnetCoreEngine(setupOptions).then(response => {

    ....

    // extract STATUS_CODE
    const regExp = new RegExp(/<meta.*?name="STATUS_CODE".*?content="(.*?)".*?\/>/);
    let statusCode = 200;
    const result = regExp.exec(response.globals.meta);
    if (result) {
      statusCode = +result[1]; // take first group
      response.globals.meta = response.globals.meta.replace(result[0], ''); // remove fake meta by full math
    }

    return ({
      html: response.html,
      globals: response.globals,
      statusCode: statusCode,
    });
  });

3) Apply Extract and set StatusCode to Response object right after prerendering on AspnetCore side.

  // Prerender / Serialize application (with Universal)
  var prerenderResult = await Prerenderer.RenderToString(
           ...
  );
  Response.StatusCode = prerenderResult.StatusCode ?? (int)HttpStatusCode.OK;
  return View();

etatuev avatar Dec 11 '17 07:12 etatuev

With new Angular CLI based template (https://github.com/aspnet/JavaScriptServices/issues/1288#issuecomment-346003334), we would need different approach.

I have an open issue at https://github.com/aspnet/JavaScriptServices/issues/1423

naveedahmed1 avatar Dec 11 '17 11:12 naveedahmed1