POST to ServiceStack Service and retrieve Location Header

妖精的绣舞 提交于 2019-11-30 19:47:55

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"); 
});
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!