Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

c# - What is the ASP.NET Core MVC equivalent to Request.RequestURI?

I found a blog post that shows how to "shim" familiar things like HttpResponseMessage back into ASP.NET Core MVC, but I want to know what's the new native way to do the same thing as the following code in a REST Post method in a Controller:

// POST audit/values
[HttpPost]
public System.Net.Http.HttpResponseMessage Post([FromBody]string value)
{
    var NewEntity = _repository.InsertFromString(value);

    var msg = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Created);
    msg.Headers.Location = new Uri(Request.RequestUri + NewEntity.ID.ToString());
    return msg;

}

In an ASP.NET Core MVC project, I can't seem to get Request.RequestUri.

I tried inspecting Request, and I was able to make a function like this:

private string UriStr(HttpRequest Request)
{
    return Request.Scheme + "://" + Request.Host + Request.Path; // Request.Path has leading /
}

So I could write UriStr(Request) instead. But I'm not sure that's right. I feel like I'm hacking my way around, and not using this correctly.

A related question for earlier non-Core ASP.NET MVC versions asks how to get the base url of the site.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Personally, I use :

new Uri(request.GetDisplayUrl())
  • GetDisplayUrl fully un-escaped form (except for the QueryString)
  • GetEncodedUrl - fully escaped form suitable for use in HTTP headers

These are extension method from the following namespace : Microsoft.AspNetCore.Http.Extensions


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...