【问题标题】:RequestUri in asp.net coreasp.net核心中的RequestUri
【发布时间】:2017-06-02 12:39:50
【问题描述】:

下面是asp.net框架中的代码

    protected HttpResponseMessage Created<T>(T apiResponse, ObjectId id) where T: ILinking
    {
        //var builder = new UriBuilder();

        Uri uri = new Uri(this.RequestUri(), id.ToString());
        apiResponse.get_Links().Add(new ApiLink(uri, "created", HttpMethod.Get));
        HttpResponseMessage message = base.Request.CreateResponse<T>(HttpStatusCode.Created, apiResponse);
        message.Headers.Add("Location", uri.ToString());
        return message;
    }

我想将它迁移到 asp.net core 中。我用谷歌搜索了很多,但找不到任何解决方案。如何在 asp.net core 中声明 this.RequestUri()?

提前致谢。

【问题讨论】:

  • 我在 .NET 世界中相对较新,但我在 6 个月前开始使用 ASP.NET Core 1.0(所以我没有以前版本的参考),但我猜你想要获取用户的实际 URI 吗?在这种情况下,下面的代码可以帮助你:string host = context.Request.Host.ToString();string path = context.Request.Path.ToString();
  • 您最初的RequestUri() 方法是怎样的?这不是标准方法。然而,假设它只返回当前请求 URI,你可以简单地使用 this.Request.RequestUri
  • 什么是“这个”?

标签: c# asp.net asp.net-core


【解决方案1】:

ASP.NET Core 包含一些新功能,可以更轻松地返回“已创建”响应。

在您的控制器中,您可以添加这样的操作。

[HttpPost, Route("create")]
public ActionResult CreateMyObject([FromBody]Creature newCreature)
{
    string id = // some new object id
    var newPath = new Uri(HttpContext.Request.Path, id);
    return this.Created(newPath);
}

【讨论】:

    猜你喜欢
    • 2017-10-23
    • 2018-05-25
    • 2021-08-21
    • 2017-06-05
    • 2017-12-17
    • 2022-01-11
    • 1970-01-01
    • 2021-09-21
    相关资源
    最近更新 更多