3

I'm trying to implement a standalone WCF REST service. One problem I currently have is that I have to send custom objects, which WebGet can't handle. So I'm trying to send them with POST instead of GET.

Now of course I can't make a JSONP request with POST data. To work around this, I have to send a ALLOW-ORIGIN header to all calls made with the "OPTIONS" HTTP-method. Is there

  • A way to apply a header to each OPTION call?
  • A way to intercept and allow all OPTION-calls without setting [WebRequest(method = "*")](instead of [WebRequest(method = "POST")]
  • A way to add the headers and return the request without it calling the WCF method?

Or alternatively, how can I override the parameter-serialization method of WebGet?

I already tried to solve this with custom Endpoints and MessageDispatchers, but it doesn't seem to work.

Andreas Arnold
  • 535
  • 5
  • 11

1 Answers1

1

I figured out how to overwrite the parameter serialization of WebGet. This question pointed me in the right direction.

I just had to overwrite the HttpBehavior and add my own QueryStringConverter, which uses the Newtonsoft JSON serializer.


    public class CustomQueryStringConverter :System.ServiceModel.Dispatcher.QueryStringConverter
        {
            public override bool CanConvert(Type type)
            {
                return true;
            }

            public override object ConvertStringToValue(string parameter, Type parameterType)
            {
                if (base.CanConvert(parameterType))
                {
                    return base.ConvertStringToValue(parameter, parameterType);
                }
                else
                {
                    object param = Newtonsoft.Json.JsonConvert.DeserializeObject(parameter, parameterType);
                    return param;
                }
            }

            public override string ConvertValueToString(object parameter, Type parameterType)
            {
                if (base.CanConvert(parameterType))
                {
                    return base.ConvertValueToString(parameter, parameterType);
                }
                else
                {
                    return Newtonsoft.Json.JsonConvert.SerializeObject(parameter);
                }
            }
        }

This also removes the need for sending OPTIONs headers and POST data.

Community
  • 1
  • 1
Andreas Arnold
  • 535
  • 5
  • 11