POST to ServiceStack Service and retrieve Location Header

后端 未结 1 1240
再見小時候
再見小時候 2021-01-05 09:03

I am trying to POST to my ServiceStack service and retrieve the Location header from the response of my CREATED entity. I am not sure whether using IReturn is valid but I am

相关标签:
1条回答
  • 2021-01-05 09:48

    See the Customizing HTTP Responses ServiceStack wiki page for all the different ways of customizing the HTTP Response.

    A HttpResult is just one way customize the HTTP Response. You generally want to include the Absolute Url if you're going to redirect it, e.g:

    public object Post(Todo todo)
    {
        var todo = ...;
        return new HttpResult(todo, HttpStatusCode.Created) { 
            Location = base.Request.AbsoluteUri.CombineWith("/tada")
        };
    }
    

    Note HTTP Clients will never see a HttpResult DTO. HttpResult is not a DTO itself, it's only purpose is to capture and modify the customized HTTP Response you want.

    All ServiceStack Clients will return is the HTTP Body, which in this case is the Todo Response DTO. The Location is indeed added to the HTTP Response headers, and to see the entire HTTP Response returned you should use a HTTP sniffer like Fiddler, WireShark or Chrome's WebInspector.

    If you want to access it using ServiceStack's HTTP Clients, you will need to add a Response Filter that gives you access to the HttpWebResponse, e.g:

    restClient.ResponseFilter = httpRes => {
          Assert.Equal(httpRes.Headers[HttpHeaders.Location], "/tada"); 
     };
    
    Todo todo = restClient.Post(new Todo { Content = "New TODO", Order = 1 });
    

    Inspecting Response Headers using Web Request Extensions

    Another lightweight alternative if you just want to inspect the HTTP Response is to use ServiceStack's Convenient WebRequest extension methods, e.g:

    var url = "http://path/to/service";
    var json = url.GetJsonFromUrl(httpRes => {
          Assert.Equal(httpRes.Headers[HttpHeaders.Location], "/tada"); 
    });
    
    0 讨论(0)
提交回复
热议问题