.NET Framework 3.5 and System.Net.Http not found - system.net

I have a framework 3.5 project containing some asmx files.
When I have exception in asmx methods, I want return an error response:
try{
...
...
catch (Exception ex)
{
var errorResponse = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent(ex.Message), ReasonPhrase = ex.Message
};
return errorResponse;
}
But I can't use HttpResponseMessage class because I can't reference Sytem.Net.Http namespace!
Can anyone help me?
Thx

System.Net.Http was introduced in 4.0, there is no 3.5 version. That's not the right return type for asmx anyways, you should go look at System.Web.

Related

.NET Core - Increase Http web api response limit

I have an API that returns a large number of data in a list.
when I am calling the API from postman I can't see the response.
i seen some solutions on google but in that they are setting
maxContentLength in web.config file.
but i haven't web.config file i have project in .net core (5.0)
There is anything that I need to do to increase API response?
here in this screenshot while debugging I can see the response.
here is the code :
[HttpPost]
[Route("ReconcileUpload")]
[Consumes("multipart/form-data")]
[RequestFormLimits(MultipartBodyLengthLimit = 268435456)]
[RequestSizeLimit(52428800)]
[hasAccess("OPRT_TXN")]
public ReconcileResponse ReconcileUpload([FromForm] IFormFile file, [FromQuery] BankChallanType FileType)
{
ReconcileResponse response = new ReconcileResponse();
string storePath = "";
using (var session = db.Database.BeginTransaction())
{
try
{
//response filling
}
catch (Exception e)
{
session.Rollback();
Logger.Error($"Error in {MethodBase.GetCurrentMethod().Name} {e.Message} at {e.StackTrace}");
throw;
}
finally
{
if (!string.IsNullOrEmpty(storePath))
System.IO.File.Delete(storePath);
}
var x= response;
return x;
}
}

created proxy with svcutil in .net core 2.2 send the request but can not get the result

I add a reference to a service in my .net core 2.2 project using svcutil 2.0.2 from here :
http://sms.magfa.com/services/urn:SOAPSmsQueue?wsdl
the created service proxy send the request to server and server send reply back to the us but the proxy can not get the result !!
we use this service in our asp .net web app but in .net core 2.2 using svcutil 2.0.2 we can not get the result.
what is the problem ?
thank you
my code :
BasicHttpBinding basicHttpBinding = null;
EndpointAddress endpointAddress = null;
ChannelFactory<ServiceReference1.SoapSmsQueuableImplChannel> factory = null;
ServiceReference1.SoapSmsQueuableImplChannel serviceProxy = null;
try
{
basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
endpointAddress = new EndpointAddress(new Uri("https://sms.magfa.com/services/urn:SOAPSmsQueue?wsdl"));
factory = new ChannelFactory<ServiceReference1.SoapSmsQueuableImplChannel>(basicHttpBinding, endpointAddress);
factory.Credentials.UserName.UserName = "**";
factory.Credentials.UserName.Password = "****";
serviceProxy = factory.CreateChannel();
//((ICommunicationObject)serviceProxy).Open();
//var opContext = new OperationContext((IClientChannel)serviceProxy);
//var prevOpContext = OperationContext.Current; // Optional if there's no way this might already be set
//OperationContext.Current = opContext;
using (var scope = new OperationContextScope((IContextChannel)serviceProxy))
{
var result = await serviceProxy.getCreditAsync("***").ConfigureAwait(false);
}
factory.Close();
((ICommunicationObject)serviceProxy).Close();
}
catch (MessageSecurityException ex)
{
throw;
}
catch (Exception ex)
{
throw;
}
finally
{
// *** ENSURE CLEANUP (this code is at the WCF GitHub page *** \\
CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}

Catch json.net serialization errors

I'm working on a web api using dotnet core 2.2 and we want to catch serialization exception and return a 400 badRequest to distinguish from the validation errors 422UnprocessableEntity. We tried to create an exception handler
public void JsonSerializerExceptionHandler(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args)
{
args.ErrorContext.Handled = true;
var errorContext = args.ErrorContext;
if (errorContext == null)
{
return;
}
var error = errorContext.Error;
throw new SerializationException(error.Message, error.InnerException);
}
but when it throw it throw an other Exception of type InvalidOperationException with message
Current error context error is different to requested error.
We tried different approach but can't find a solution. Can someone help?
Maybe my solution will be useful for somebody.
I need to catch JSON.NET serialization or deserialization exception and handle it in my .NET Core middleware.
Add rethrow json.net exception in JSON.NET SerializerSettings
services.AddControllers().AddNewtonsoftJson(options => {
//your options here
options.SerializerSettings.Error += (sender, args) => throw args.ErrorContext.Error;
});
Add catch on middleware handler and override JsonSerializationException:
if (exception is JsonSerializationException)
{
var exceptionMessage = exception.InnerException != null ?
exception.InnerException.Message : exception.Message;
exception = new BadRequestException(ApiErrorCode.InvalidResourceModel,
exceptionMessage);
}

Custom InputFormatter on PostAsync exception in ASP NET Core

I have a strange problem that I don't know why is giving problems:
On client, I have this code:
HttpResponseMessage response = await _httpClient.PostAsync("http://127.0.0.1:5544/api/Blablabla", new StringContent("test"));
On server, I have implemented a custom InputFormatter that have this
public async override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
var request = context.HttpContext.Request;
try
{
using (var reader = new StreamReader(request.Body))
{
var content = await reader.ReadToEndAsync().ConfigureAwait(false);
return await InputFormatterResult.SuccessAsync(content).ConfigureAwait(false);
}
}
catch (Exception e)
{
return await InputFormatterResult.FailureAsync();
}
}
If I try this, the catch exception of the server is fired, giving me an exception of:
An existing connection was forcibly closed by the remote host
But.....
If in the client I make the PostAsync "sync" doing this:
HttpResponseMessage response = _httpClient.PostAsync("http://127.0.0.1:5544/api/Blablabla", new StringContent("test")).Result;
Everything works ok.
What's the problem???
Ok, I fixed it...
The problem was, as you can imagine, that the function that called postasync was async, but the one before was not, and I did not make a .Wait() to that one.
Was nothing related to asp net core, just a problem of async code from sync code.

WCF FaultException<T> is not caught in client, instead caught as service fault

I have service configured for FaultException but on the client end I am not getting the exception caught in
catch (FaultException<MyServiceFault> fe)
{
}
instead it is always caught in
catch (FaultException fx)
{
}
I am using selfhost and channelfactory.
my Service:
[FaultContract(typeof(MyServiceFault))]
public string HelloWorld()
{
int a=5;
try
{
var b = a/0;
}
catch(Exception e)
{
throw new FaultException<MyServiceFault>(new MyServiceFault(){Message ="Divide by zero"}, "Divide by Zero");
}
}
I also have the [DataContract] attribute on the MyServiceFault.
I am wondering if I miss any configuration.
I've answered a similar question here: Proper way to throw exception over WCF
Try to declare your operation like this:
[FaultContractAttribute(
typeof(MyServiceFault),
Action = "",
Name = "MyServiceFault",
Namespace = "YourNamespace")]
public string HelloWorld()
Hope it helps.