programing

ASP를 강제하는 방법이 있나요?일반 텍스트를 반환하려면 NET Web API를 선택하십시오.

cafebook 2023. 4. 23. 11:28
반응형

ASP를 강제하는 방법이 있나요?일반 텍스트를 반환하려면 NET Web API를 선택하십시오.

ASP에서 일반 텍스트로 답변을 받아야 합니다.NET Web API 컨트롤러.

부탁해 본 적이 있습니다.Accept: text/plain효과가 없는 것 같아요게다가, 그 요청은 외부적이고 내가 통제할 수 없는 것이다.오래된 ASP를 흉내내는 것입니다.인터넷 방식:

context.Response.ContentType = "text/plain";
context.Response.Write("some text);

좋은 생각 있어요?

편집, 솔루션:Aliostad의 답변을 바탕으로 WebAPIContrib 텍스트포메터를 추가하여 Application_Start에서 초기화했습니다.

  config.Formatters.Add(new PlainTextFormatter());

제 컨트롤러는 이렇게 되어버렸습니다.

[HttpGet, HttpPost]
public HttpResponseMessage GetPlainText()
{
  return ControllerContext.Request.CreateResponse(HttpStatusCode.OK, "Test data", "text/plain");
}

음... 이 작업을 수행하기 위해 사용자 지정 포맷터를 만들 필요는 없을 것 같습니다.대신 다음과 같이 내용을 반환합니다.

    [HttpGet]
    public HttpResponseMessage HelloWorld()
    {
        string result = "Hello world! Time is: " + DateTime.Now;
        var resp = new HttpResponseMessage(HttpStatusCode.OK);
        resp.Content = new StringContent(result, System.Text.Encoding.UTF8, "text/plain");
        return resp;
    }

커스텀 포메터를 사용하지 않고 사용할 수 있습니다.

명시적으로 출력을 생성하고 Accept 헤더를 기반으로 기본 콘텐츠 협상을 재정의하려면 사용하지 마십시오.Request.CreateResponse()MIME 타입을 강제하기 때문입니다.

대신 명시적으로 새로 만듭니다.HttpResponseMessage내용을 수동으로 할당합니다.위의 예에서는StringContent그러나 다양한 데이터로부터 데이터를 반환할 수 있는 다른 컨텐츠 클래스가 꽤 있습니다.NET 데이터 유형/구조

.net core의 경우:

[HttpGet("About")]
public ContentResult About()
{
    return Content("About text");
}

https://learn.microsoft.com/en-us/aspnet/core/mvc/models/formatting

종속성을 추가하지 않고 단순한 플레인/텍스트 포맷을 찾는 경우 이 방법이 효과적입니다.

public class TextPlainFormatter : MediaTypeFormatter
{
    public TextPlainFormatter()
    {
        this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
    }

    public override bool CanWriteType(Type type)
    {
        return type == typeof(string);
    }

    public override bool CanReadType(Type type)
    {
        return type == typeof(string);
    }

    public override Task WriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, TransportContext transportContext)
    {
        return Task.Factory.StartNew(() => {
            StreamWriter writer = new StreamWriter(stream);
            writer.Write(value);
            writer.Flush();
        });
    }

    public override Task<object> ReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, IFormatterLogger formatterLogger)
    {
        return Task.Factory.StartNew(() => {
            StreamReader reader = new StreamReader(stream);
            return (object)reader.ReadToEnd();
        });
    }
}

Global web api 설정에 추가하는 것을 잊지 마십시오.

config.Formatters.Add(new TextPlainFormatter());

이제 문자열 개체를 다음 주소로 전달할 수 있습니다.

this.Request.CreateResponse(HttpStatusCode.OK, "some text", "text/plain");
  • ASP의 콘텍스트를 사용하지 않도록 주의해 주세요.NET Web API를 이용하지 않으면 조만간 후회하게 될 것입니다.ASP의 비동기 특성.NET Web API를 사용하여HttpContext.Current부채
  • 일반 텍스트 포맷터를 사용하여 포맷터에 추가합니다.주변에 수십 개가 있습니다.당신은 심지어 당신의 것을 쉽게 쓸 수 있었다.WebApiContrib에는 1개가 있습니다.
  • content type header를 설정하여 강제로 설정할 수 있습니다.httpResponseMessage.Headers로.text/plain플레인 텍스트포맷을 등록한 경우 컨트롤러로 합니다.

동의: 텍스트/일반이 작동하지 않는 경우 텍스트 MIME 유형에 등록된 형식 지정기가 없습니다.

서비스 컨피규레이션에서 지원되는 모든 포메터의 목록을 가져오면 지정된 MIME 유형의 포메터가 없음을 확인할 수 있습니다.

텍스트 MIME 유형을 지원하는 매우 간단한 미디어 유형 포맷터를 생성합니다.

http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters

다음과 같은 확장자는 줄 수를 줄이고 코드를 아름답게 만들 수 있습니다.

public static class CommonExtensions
{
    public static HttpResponseMessage ToHttpResponseMessage(this string str)
    {
        var resp = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StringContent(str, System.Text.Encoding.UTF8, "text/plain")
        };

        return resp;
    }
}


으로, 「」에 끝난 번호를 할 수 있게 .Web API:

public class HomeController : ApiController
{
    [System.Web.Http.HttpGet]
    public HttpResponseMessage Index()
    {
        return "Salam".ToHttpResponseMessage();
    }
}


에 의해{DOMAIN}/api/Home/Index다음과 같은 일반 텍스트를 볼 수 있습니다.

MyPlainTextResponse

언급URL : https://stackoverflow.com/questions/11581697/is-there-a-way-to-force-asp-net-web-api-to-return-plain-text

반응형